﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;

namespace System
{
    /// <summary>
    /// 枚举扩展方法类
    /// </summary>
    public static class EnumEx
    {
        /// <summary>
        /// 获取枚举项的Description特性的描述文字
        /// </summary>
        /// <param name="enumvalue"> </param>
        /// <returns> </returns>
        public static string ToDescription(this Enum enumvalue)
        {
            Type type = enumvalue.GetType();
            MemberInfo[] members = type.GetMember(enumvalue.CastTo<string>());
            if (members.Length > 0)
            {
                return members[0].ToDescription();
            }
            return enumvalue.CastTo<string>();
        }
        /// <summary>
        /// 获取枚举序列集
        /// <para>值 描述 名称</para>
        /// </summary>
        /// <param name="enumvalue"></param>
        /// <returns>值 描述 名称</returns>
        public static List<Tuple<int, string, string>> ToTuple(this Enum enumvalue)
        {
            List<Tuple<int, string, string>> result = new List<Tuple<int, string, string>>();
            Type type = enumvalue.GetType();
            var values = Enum.GetValues(type);
            foreach (Enum item in values)
            {
                int v = Convert.ToInt32(item);
                string n = Enum.GetName(type, item);
                string d = item.ToDescription();
                Tuple<int, string, string> _tmp = new Tuple<int, string, string>(v, d, n);
                result.Add(_tmp);
            }
            return result;
        }
        /// <summary>
        /// 整型转成对应枚举
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="source"></param>
        /// <param name="defaultvalue"></param>
        /// <returns></returns>
        public static T ToEnum<T>(this int source, T defaultvalue)
        {
            var t = typeof(T);
            if (t.IsEnum)
            {
                var attrs = t.GetCustomAttributes(typeof(FlagsAttribute), false);
                if (attrs.Length == 1)
                {
                    return (T)Enum.ToObject(t, source);
                }
                else
                {
                    if (Enum.IsDefined(t, source))
                    {
                        return (T)Enum.ToObject(t, source);
                    }
                }
            }
            return defaultvalue;
        }
    }
}
